package com.cn.customer.housekeeping.housekeepingc.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cn.customer.housekeeping.housekeepingc.R;
import com.cn.customer.housekeeping.housekeepingc.bean.BaseResp;
import com.cn.customer.housekeeping.housekeepingc.bean.UserResp;
import com.cn.customer.housekeeping.housekeepingc.biz.personcenter.IUserLoginView;
import com.cn.customer.housekeeping.housekeepingc.biz.personcenter.InterfacePresenter;
import com.cn.customer.housekeeping.housekeepingc.bridge.BridgeFactory;
import com.cn.customer.housekeeping.housekeepingc.bridge.Bridges;
import com.cn.customer.housekeeping.housekeepingc.bridge.cache.sharePref.EBSharedPrefManager;
import com.cn.customer.housekeeping.housekeepingc.bridge.cache.sharePref.EBSharedPrefUser;
import com.cn.customer.housekeeping.housekeepingc.constant.URLUtil;
import com.cn.customer.housekeeping.housekeepingc.ui.base.BaseActivity;
import com.cn.customer.housekeeping.housekeepingc.util.NavUtils;
import com.cn.customer.housekeeping.housekeepingc.util.NetworkUtil;
import com.cn.customer.housekeeping.housekeepingc.util.SecurityUtils;
import com.cn.customer.housekeeping.housekeepingc.util.StringUtil;
import com.cn.customer.housekeeping.housekeepingc.util.ToastUtil;
import com.cn.customer.housekeeping.housekeepingc.view.CountDownTimerUtils;
import com.google.gson.Gson;


/***
 * 注册
 */
public class RegisterActivity extends BaseActivity implements IUserLoginView {
    private InterfacePresenter mInterfacePresenter;
    private TextView tvLogin, tvGetValidateCode;
    private LinearLayout ll_xieyi;
    private EditText mPhoneDn, etPassword, et_verification;
    private String ePassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_register);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initViews() {
        mInterfacePresenter = new InterfacePresenter();
        mInterfacePresenter.attachView(this);
        tvLogin = (TextView) findViewById(R.id.tv_login);
        mPhoneDn = (EditText) findViewById(R.id.phone_dn);
        etPassword = (EditText) findViewById(R.id.et_password);
        et_verification = (EditText) findViewById(R.id.et_verification);
        ll_xieyi = (LinearLayout) findViewById(R.id.ll_xieyi);
        tvGetValidateCode = (TextView) findViewById(R.id.tv_get_validate_code);
    }

    @Override
    public void initData() {
//        type = getIntent().getExtras().getString(Constants.TYPE);
    }

    @Override
    public void initListeners() {
        tvLogin.setOnClickListener(this);
        ll_xieyi.setOnClickListener(this);
        tvGetValidateCode.setOnClickListener(this);
        mPhoneDn.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence str, int arg1, int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String phoneNumber = mPhoneDn.getText().toString().replace(" ", "");
                if (!StringUtil.isEmpty(phoneNumber)) {
                    if (!StringUtil.isMobileNO(phoneNumber)) {
                        tvGetValidateCode.setEnabled(false);
                        tvGetValidateCode.setTextColor(RegisterActivity.this.getResources().getColor(R.color.white));
                    } else {
                        tvGetValidateCode.setEnabled(true);
                        tvGetValidateCode.setTextColor(RegisterActivity.this.getResources().getColor(R.color.white));
                    }
                } else {
                    tvGetValidateCode.setTextColor(RegisterActivity.this.getResources().getColor(R.color.white));
                    tvGetValidateCode.setEnabled(false);
                }
            }
        });
    }


    @Override
    public void setHeader() {
        super.setHeader();
        rlTitle.setVisibility(View.GONE);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login: //注册
                String phoneNumber = mPhoneDn.getText().toString().replace(" ", "");
                ePassword = etPassword.getText().toString();

                mInterfacePresenter.getRegist(phoneNumber, et_verification.getText().toString(),  SecurityUtils.get32MD5Str(etPassword.getText().toString()) );
                break;
            case R.id.ll_xieyi://协议
                NavUtils.gotoWebviewActivity(RegisterActivity.this, "http://api.sy.lemoncc.com/service.html", "注册协议");

                break;
            case R.id.tv_get_validate_code://验证码
                if (validatePhoneNumber(mPhoneDn.getText().toString().replace(" ", ""))) {
                    CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(tvGetValidateCode, 60000, 1000, RegisterActivity.this);
                    mCountDownTimerUtils.start();
                    //获取验证码接口
                    mInterfacePresenter.getVerifyCode(mPhoneDn.getText().toString().replace(" ", ""));
                }
                break;


        }
        super.onClick(v);
    }


    @Override
    public void onError(BaseResp s) {
        if (s.getUrl().contains(URLUtil.url_get_getVerifyCode)) {//验证码
            ToastUtil.makeText(RegisterActivity.this, s.getMessage());
        }
    }
    EBSharedPrefManager manager = BridgeFactory.getBridge(Bridges.SHARED_PREFERENCE);
    UserResp mUserResp;

    @Override
    public void onSuccess(BaseResp s) {
        if (s.getUrl().contains(URLUtil.url_get_getVerifyCode)) {//验证码
            ToastUtil.makeText(RegisterActivity.this, "获取成功");

        } else if (s.getUrl().contains(URLUtil.url_get_regist)) {//注册
            ToastUtil.makeText(RegisterActivity.this, "注册成功");
            Gson gson = new Gson();
            mUserResp = gson.fromJson(s.getData(), UserResp.class);
            manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.userid, mUserResp.getUserid() );
            manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.avatar, mUserResp.getAvatar() );
            manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.phone, mUserResp.getPhone() );
            manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.gender, mUserResp.getGender() );
            manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.username, mUserResp.getUsername());
            manager.getKDPreferenceUserInfo().saveBoolean(EBSharedPrefUser.isLogin, true);
            NavUtils.gotoTabMainActivity(RegisterActivity.this);

        }


    }


    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }


    /**
     * 验证手机号码是否合乎规则
     */
    private boolean validatePhoneNumber(String phoneNumbers) {
        String phoneNumber = phoneNumbers.replace(" ", "");
        if (!NetworkUtil.isNetworkAvailable(this)) {
            ToastUtil.makeText(this, "您的网络异常,请检查网络后重新尝试");
            return false;
        }
        if (!StringUtil.isMobileNO(phoneNumber)) {
            ToastUtil.makeText(this, "请输入正确的手机号码");
            return false;
        }
        return true;
    }


    /**
     * 验证手机号\动态验证码
     */
    private boolean validateCode(String phoneNumbers, String validateCode) {
        String phoneNumber = phoneNumbers.replace(" ", "");
        if (!NetworkUtil.isNetworkAvailable(this)) {
            ToastUtil.makeText(this, "您的网络异常,请检查网络后重新尝试");
            return false;
        }
        if (!validatePhoneNumber(phoneNumber))
            return false;

//        if (!isVerifyCodeRight(validateCode)) {
//            ToastUtil.makeText(this, "验证码错误，请重新输入");
//            return false;
//        }

        return true;
    }

    /**
     * @return
     * @Description 判断是否为6位验证码
     */

    private boolean isVerifyCodeRight(String validateCode) {
        return validateCode.matches("\\d{4}");
    }

    /**
     * 密码的正确性
     */
    private boolean validate(String password) {
        if (!NetworkUtil.isNetworkAvailable(this)) {
            ToastUtil.makeText(this, "您的网络异常,请检查网络后重新尝试");
            return false;
        }
        if (password.length() < 6 || password.length() > 20) {
            ToastUtil.makeText(this, "您的密码输入错误，请重新输入");
            return false;
        }

        return true;
    }


}
